/*
 * DCE400服务系统 -- 后端服务接口 -- 前端配置
 * 包括：阅读注册管理协议
 *      平台须知
 *      留言须知
 *      子公司链接
 */

package frontsetting

import (
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/dao"
	entity2 "gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/db"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
	"time"
)

//********************************************
//Func  ：查询注册协议
//Method：GET
//Usage ：注册 - 注册协议
//********************************************
func QueryRegistrationProtocol(c *gin.Context) {
	userId := c.DefaultQuery("userId", "")                //查询人
	futureCoLtdId := c.DefaultQuery("futuresCoLtdId", "") //版本、公司标识
	global.Log.Info("QueryRegistrationProtocol: ", zap.Any(userId, futureCoLtdId))

	/*
		//这个查询符合条件的一组输出
		decarations := []*entity.Declaration{}
		err:=db.Session().Table("declaration").Where("type=?", entity.EDeclarationType_Registration).Find( &decarations )
		if err!=nil{
			global.Log.Error("QueryRegistrationProtocol query declaration failed, Error:", zap.Any("error",err) )
		}
	*/

	var decaration entity2.Declaration
	_, err := db.Session().Table("declaration").Where("type=?", entity2.EDeclarationType_Registration).Get(&decaration)
	if err != nil {
		global.Log.Error("QueryRegistrationProtocol query declaration failed, Error:", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("未找到注册协议信息"))
		return
	}
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", decaration))
}

//********************************************
//Func  ：更新注册协议内容/没有则插入
//Method：POST
//Usage ：注册 - 注册协议
//********************************************
func UpdateRegistrationProtocol(c *gin.Context) {
	var err error
	var decaration entity2.Declaration
	idStr := c.DefaultPostForm("id", "") //id号
	if idStr != "" {
		decaration.Id, _ = strconv.ParseInt(idStr, 10, 64)
		if err != nil {
			global.Log.Error("QueryRegistrationProtocol decaration.Id failed:", zap.Any("decaration.Id:", err))
		}
	}
	decaration.Author = c.DefaultPostForm("userId", "")   //修改者
	decaration.Text = c.DefaultPostForm("text", "")       //text
	decaration.EngText = c.DefaultPostForm("engText", "") //text
	decaration.Describ = c.DefaultPostForm("describ", "") //text

	decaration.Type = entity2.EDeclarationType_Registration
	global.Log.Info("QueryRegistrationProtocol: ", zap.Any("Registration:", decaration))
	newdecaration, err := dao.UpdateDecarationInfo(&decaration)
	/*
		session := db.Session().Table("declaration")
		defer session.Close()
		var temp entity.Declaration
		has, err := session.Where("type=?", entity.EDeclarationType_Registration).Get(&temp)
		if err != nil {
			global.Log.Error("UpdateRegistrationProtocol query declaration failed, Error:", zap.Any("error", err))
			c.JSON(http.StatusOK, model.Fail("操作失败"))
			return
		}

		cnt := int64(0)
		err = session.Begin()
		if err != nil {
			global.Log.Error("UpdateRegistrationProtocol begin failed, Error:", zap.Any("error", err))
			c.JSON(http.StatusOK, model.Fail("操作失败"))
			return
		}

		if has {
			decaration.EditedAt = time.Now()
			decaration.CreatedAt = temp.CreatedAt
			cnt, err = session.Cols("text,engText,describ").
				Where("id=? and type=?", decaration.Id, entity.EDeclarationType_Registration).
				Update(&decaration) //更新
		} else {
			decaration.CreatedAt = time.Now()
			decaration.Id = util.GenSnowflakeInt64()
			cnt, err = session.Insert(&decaration) //插入
		}
		if err != nil {
			session.Rollback()
			global.Log.Error("UpdateRegistrationProtocol write db failed, Error:", zap.Any("error", err), zap.Any("cnt", cnt))
			c.JSON(http.StatusOK, model.Fail("操作失败"))
			return
		}
		err = session.Commit()
		if err != nil {
			global.Log.Error("UpdateRegistrationProtocol commit failed, Error:", zap.Any("error", err))
		}
	*/
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", decaration))
	global.Log.Info("UpdateRegistrationProtocol success, new decaration:", zap.Any("new decaration", newdecaration))
}

//********************************************
//Func  ：查询平台须知
//Method：GET
//Usage ：注册
//********************************************
func QueryPlatformNotice(c *gin.Context) {

	userId := c.DefaultQuery("userId", "")                //查询人
	futureCoLtdId := c.DefaultQuery("futuresCoLtdId", "") //版本、公司标识
	global.Log.Info("QueryPlatformNotice: ", zap.Any(userId, futureCoLtdId))

	var decaration entity2.Declaration
	_, err := db.Session().Table("declaration").Where("type=?", entity2.EDeclarationType_Platform).Get(&decaration)
	if err != nil {
		global.Log.Error("QueryPlatformNotice query declaration failed, Error:", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("未找到平台须知信息"))
		return
	}
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", decaration))
}

//********************************************
//Func   更新平台须知
//Method：POST
//Usage ：注册
//********************************************
func UpdatePlatformNotice(c *gin.Context) {

	decaration, err := dao.QueryMessageNotice()
	decaration.Author = c.DefaultPostForm("userId", "")   //修改者
	decaration.Text = c.DefaultPostForm("text", "")       //text
	decaration.EngText = c.DefaultPostForm("engText", "") //text
	decaration.Describ = c.DefaultPostForm("describ", "") //text
	decaration.Type = entity2.EDeclarationType_Platform
	global.Log.Info("UpdatePlatformNotice: ", zap.Any("Registration:", decaration))
	newDecaration, err := dao.UpdateDecarationInfo(decaration)
	if err != nil {
		c.JSON(http.StatusOK, model.SuccessObject("操作失败", err))
	} else {
		c.JSON(http.StatusOK, model.SuccessObject("操作成功", newDecaration))
	}
	global.Log.Info("UpdatePlatformNotice success, new decaration:", zap.Any("new decaration", decaration))
}

//********************************************
//Func  ：查询留言须知
//Method：GET
//Usage ：反馈
//********************************************
func QueryMessageNotice(c *gin.Context) {
	userId := c.DefaultQuery("userId", "")                //查询人
	futureCoLtdId := c.DefaultQuery("futuresCoLtdId", "") //版本、公司标识
	global.Log.Info("QueryMessageNotice: ", zap.Any(userId, futureCoLtdId))

	var decaration entity2.Declaration
	_, err := db.Session().Table("declaration").Where("type=?", entity2.EDeclarationType_Message).Get(&decaration)
	if err != nil {
		global.Log.Error("QueryMessageNotice query declaration failed, Error:", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("未找到留言须知信息"))
		return
	}
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", decaration))
}

//********************************************
//Func  ：更新留言须知
//Method：POST
//Usage ：反馈
//********************************************
func UpdateMessageNotice(c *gin.Context) {
	decaration, err := dao.QueryMessageNotice()
	decaration.Author = c.DefaultPostForm("userId", "")   //修改者
	decaration.Text = c.DefaultPostForm("text", "")       //text
	decaration.EngText = c.DefaultPostForm("engText", "") //text
	decaration.Describ = c.DefaultPostForm("describ", "") //text
	decaration.Type = entity2.EDeclarationType_Message
	global.Log.Info("UpdateMessageNotice: ", zap.Any("Registration:", decaration))
	newDecaration, err := dao.UpdateDecarationInfo(decaration)
	if err != nil {
		c.JSON(http.StatusOK, model.SuccessObject("操作失败", err))
		global.Log.Error("UpdateMessageNotice call dao failed:", zap.Any("error", err))
	} else {
		c.JSON(http.StatusOK, model.SuccessObject("操作成功", newDecaration))
		global.Log.Info("UpdateMessageNotice success, new decaration:", zap.Any("new decaration", decaration))
	}
}

//********************************************
//Func  ：查询子公司链接/友情链接 列表
//Method：GET
//Usage ：首页
//********************************************
func QueryFriendshipLinks(c *gin.Context) {
	pageSize, err1 := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	if err1 != nil {
		global.Log.Error("QueryFriendshipLinks input param pagesize error:", zap.Any("error", err1))
		c.JSON(http.StatusOK, model.Fail("请求参数错误"))
		return
	}

	page, err2 := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err2 != nil {
		global.Log.Error("QueryFriendshipLinks input param page error:", zap.Any("error", err2))
		c.JSON(http.StatusOK, model.Fail("请求参数错误"))
		return
	}

	userId := c.DefaultQuery("userId", "")                //查询人
	futureCoLtdId := c.DefaultQuery("futuresCoLtdId", "") //版本、公司标识
	global.Log.Info("QueryFriendshipLinks: ", zap.Any(userId, futureCoLtdId))
	status, _ := strconv.Atoi(c.DefaultQuery("status", "-1"))

	total, links, err := dao.QueryFriendshipLinks(page, pageSize, entity2.EPublishStatus(status))
	if err != nil {
		global.Log.Error("QueryFriendshipLinks query friendlinks failed, Error:", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("未找到友情链接信息"))
		return
	}

	type FriendshipLinkList struct { //列表查询输出
		Total int64
		List  []*entity2.FriendshipLink
	}

	output := &FriendshipLinkList{
		Total: total,
		List:  links,
	}
	global.Log.Info("QueryFriendshipLinks query friendlinks success.", zap.Any("friendlinks", output))
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", output))
}

//********************************************
//Func  ：新增子公司链接/友情链接
//Method：POST
//Usage ：首页
//********************************************
func InsertFriendshipLink(c *gin.Context) {
	var err error
	var link entity2.FriendshipLink
	link.Title = strings.TrimSpace(c.DefaultPostForm("title", "")) //text
	if len(link.Title) <= 0 {
		c.JSON(http.StatusOK, model.Fail("标题不能为空"))
		return
	}

	link.Url = c.DefaultPostForm("url", "") //text
	if len(strings.TrimSpace(link.Url)) <= 0 {
		c.JSON(http.StatusOK, model.Fail("链接不能为空"))
		return
	}
	link.CreatedAt = time.Now()
	link.LogoUrl = c.DefaultPostForm("logoUrl", "")              //text
	link.PublishStatus = int(entity2.EPublishStatus_Unpublished) //未发布
	link.SortIndex, _ = strconv.Atoi(c.DefaultPostForm("sortIndex", "-1"))

	global.Log.Info("InsertFriendshipLink: ", zap.Any("link:", link))
	newlink, err := dao.InsertFriendshipLink(&link)
	if err != nil {
		global.Log.Error("InsertFriendshipLink dao.InsertFriendshipLink failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("操作失败"))
		return
	}

	c.JSON(http.StatusOK, model.SuccessObject("操作成功", newlink))
	global.Log.Info("InsertFriendshipLink success.", zap.Any("new link", newlink))
}

//********************************************
//Func  ：删除子公司链接/友情链接
//Method：DELETE
//Usage ：首页
//********************************************
func DeleteFriendshipLink(c *gin.Context) {
	idStr := c.DefaultQuery("id", "") //text
	if len(strings.TrimSpace(idStr)) <= 0 {
		c.JSON(http.StatusOK, model.Fail("链接ID不能为空"))
		return
	}

	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		global.Log.Error("ParseInt failed: Id:", zap.Any("id:", idStr), zap.Any("error:", err))
	}

	global.Log.Info("DeleteFriendshipLink: Id:", zap.Any("id:", idStr))
	err = dao.DeleteFriendshipLink(id)
	if err != nil {
		global.Log.Error("call dao.DeleteFriendshipLink failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("操作失败"))
		return
	}

	global.Log.Info("DeleteFriendshipLink success, del link:", zap.Any("link", id))
	c.JSON(http.StatusOK, model.Success("操作成功"))
}

//********************************************
//Func  ：更新子公司链接/友情链接
//Method：POST
//Usage ：首页
//********************************************
func UpdateFriendshipLink(c *gin.Context) {
	var err error

	var link entity2.FriendshipLink
	idStr := c.DefaultPostForm("id", "") //text
	if idStr == "" {
		c.JSON(http.StatusOK, model.Fail("未指明待修改的链接"))
		return
	}
	link.Id, err = strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		global.Log.Error("UpdateFriendshipLink link.Id failed:", zap.Any("link.Id:", err))
	}

	link.Title = strings.TrimSpace(c.DefaultPostForm("title", ""))
	link.Url = c.DefaultPostForm("url", "")         //text
	link.LogoUrl = c.DefaultPostForm("logoUrl", "") //text
	link.SortIndex, _ = strconv.Atoi(c.DefaultPostForm("sortIndex", "-1"))

	newlink, err := dao.UpdateFriendshipLink(&link)
	if err != nil {
		global.Log.Error("call dao.UpdateFriendshipLink failed.", zap.Any("error", err))
		c.JSON(http.StatusOK, model.Fail("操作失败"))
		return
	}
	c.JSON(http.StatusOK, model.SuccessObject("操作成功", newlink))
	global.Log.Info("UpdateFriendshipLink success, link:", zap.Any("link", newlink))

}

//********************************************
//Func  ：状态更新子公司链接/友情链接
//Method：POST
//Usage ：首页
//********************************************
func SetFriendshipLinkStatus(c *gin.Context) {
	var err error
	var link entity2.FriendshipLink
	idStr := c.DefaultPostForm("id", "") //text
	if idStr == "" {
		c.JSON(http.StatusOK, model.Fail("未指明待修改的链接"))
		return
	}
	link.Id, _ = strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		global.Log.Error("SetFriendshipLinkStatus decaration.Id failed:", zap.Any("decaration.Id:", err))
	}

	statusStr := c.DefaultPostForm("status", "")
	status, err := strconv.Atoi(strings.TrimSpace(statusStr))
	if status < int(entity2.EPublishStatus_Unpublished) || status > int(entity2.EPublishStatus_Deleted) {
		c.JSON(http.StatusOK, model.Fail("未知状态码"))
		return
	}

	err = dao.SetFriendshipLinkStatus(link.Id, status)
	if err != nil {
		c.JSON(http.StatusOK, model.Fail("操作失败"))
		global.Log.Error("dao.SetFriendshipLinkStatus failed, Error:", zap.Any("error", err))
	} else {
		c.JSON(http.StatusOK, model.Success("操作成功"))
		global.Log.Info("dao.SetFriendshipLinkStatus success, link:", zap.Any("link", link))
	}
}
